package cn.wit.summit.chwan.widgets.ptr.header;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.View;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.widgets.ptr.PtrFrameLayout;
import cn.wit.summit.chwan.widgets.ptr.PtrUIHeader;
import cn.wit.summit.chwan.widgets.ptr.indicator.PtrIndicator;
import cn.wit.summit.chwan.widgets.refreshLayout.util.DensityUtil;

public class ChwHeaderView extends PtrUIHeader {

    private AnimationDrawable mDrawable;
    private int               mDrawableWidth, mDrawableHeight;
    private PtrFrameLayout mPtrFrameLayout;

//    private float mScale = 1f;
//    private Animation mScaleAnimation = new Animation() {
//        @Override
//        public void applyTransformation(float interpolatedTime, Transformation t) {
//            mScale = 1f - interpolatedTime;
//            mDrawable.setAlpha((int) (255 * mScale));
//            invalidate();
//        }
//    };

    public ChwHeaderView(Context context) {
        super(context);
        initView();
    }

    public ChwHeaderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public ChwHeaderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    public void setPtrFrameLayout(PtrFrameLayout layout) {

//        final PtrUIHandlerHook mPtrUIHandlerHook = new PtrUIHandlerHook() {
//            @Override
//            public void run() {
//                startAnimation(mScaleAnimation);
//            }
//        };
//
//        mScaleAnimation.setDuration(200);
//        mScaleAnimation.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//
//            }
//
//            @Override
//            public void onAnimationEnd(Animation animation) {
//                mPtrUIHandlerHook.resume();
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//
//            }
//        });

        mPtrFrameLayout = layout;
//        mPtrFrameLayout.setRefreshCompleteHook(mPtrUIHandlerHook);
    }

    private void initView() {
//        mDrawable = new MaterialProgressDrawable(getContext(), this);
        mDrawable = (AnimationDrawable) getResources().getDrawable(R.drawable.header_loading_drawable);
//        mDrawable.setBackgroundColor(Color.WHITE);
        setBackgroundDrawable(mDrawable);
        mDrawable.setCallback(this);

        final DensityUtil density = new DensityUtil();
        int               w       = density.dip2px(34);
        int               h       = density.dip2px(24);

        mDrawableWidth = w;
        mDrawableHeight = h;
    }

    @Override
    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
        LogUtils.e("scheduleDrawable");
        super.scheduleDrawable(who, what, when);
    }

    @Override
    public void invalidateDrawable(Drawable dr) {
        LogUtils.e("invalidateDrawable");
        if (dr == mDrawable) {
            invalidate();
        } else {
            super.invalidateDrawable(dr);
        }
    }

//    public void setColorSchemeColors(int[] colors) {
//        mDrawable.setColorSchemeColors(colors);
//        invalidate();
//    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = mDrawable.getIntrinsicHeight() + getPaddingTop() + getPaddingBottom();

        height = mDrawableHeight * 2;

        heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
//        mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        final int saveCount = canvas.save();
//        Rect      rect      = mDrawable.getBounds();
        int l = getPaddingLeft() + (getMeasuredWidth() - mDrawableWidth) / 2;
        int t = getPaddingTop() + (getMeasuredHeight() - mDrawableHeight) / 2;
//        canvas.translate(l, getPaddingTop());
//        canvas.translate(l, mDrawableHeight / 2);
//        canvas.scale(mScale, mScale, rect.exactCenterX(), rect.exactCenterY());
        if (mDrawable.isRunning()) {
            LogUtils.e("isRunning");
            mDrawable.setBounds(l, t, l + mDrawableWidth, t + mDrawableHeight);
//            mDrawable.getCurrent().draw(canvas);
        } else {
            LogUtils.e("isRunning-else");
            mDrawable.draw(canvas);
        }
        canvas.restoreToCount(saveCount);
    }

    /**
     * When the content view has reached top and refresh has been completed, view will be reset.
     *
     * @param frame
     */
    @Override
    public void onUIReset(PtrFrameLayout frame) {
        LogUtils.e("isRunning");
//        mScale = 1f;
        mDrawable.stop();
    }

    /**
     * prepare for loading
     *
     * @param frame
     */
    @Override
    public void onUIRefreshPrepare(PtrFrameLayout frame) {
        LogUtils.e("isRunning");
    }

    /**
     * perform refreshing UI
     *
     * @param frame
     */
    @Override
    public void onUIRefreshBegin(PtrFrameLayout frame) {
        LogUtils.e("isRunning");
//        mDrawable.setAlpha(255);
        mDrawable.start();
    }

    /**
     * perform UI after refresh
     *
     * @param frame
     */
    @Override
    public void onUIRefreshComplete(PtrFrameLayout frame) {
        LogUtils.e("isRunning");
        mDrawable.stop();
    }

    @Override
    public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {

        LogUtils.e("isRunning");
//        float percent = Math.min(1f, ptrIndicator.getCurrentPercent());
//
//        if (status == PtrFrameLayout.PTR_STATUS_PREPARE) {
//            mDrawable.setAlpha((int) (255 * percent));
//            mDrawable.showArrow(true);
//
//            float strokeStart = ((percent) * .8f);
//            mDrawable.setStartEndTrim(0f, Math.min(0.8f, strokeStart));
//            mDrawable.setArrowScale(Math.min(1f, percent));
//
//            // magic
//            float rotation = (-0.25f + .4f * percent + percent * 2) * .5f;
//            mDrawable.setProgressRotation(rotation);
//            invalidate();
//        }
    }

}
